package com.github.yoojia.flow.util;

import com.parkingwang.lang.Try;
import com.parkingwang.lang.data.Config;
import com.parkingwang.lang.kit.StringKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.file.Paths;
import java.util.Map;

/**
 * 配置加载器
 *
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.3
 */
public class ConfigKit {

    public static final Logger LOGGER = LoggerFactory.getLogger(ConfigKit.class);

    private ConfigKit() {
    }

    public static Config empty() {
        return new Config();
    }

    @SuppressWarnings("unchecked")
    public static Config stream(final InputStream stream) {
        return Try.die(() ->
                new Config((Map<String, Object>) new Yaml().load(stream)));
    }

    public static void extractByName(final String srcName, final String outputName) {
        final String dir = System.getProperty("user.dir");
        Try.ignore(() -> {
            final File outputFile = Paths.get(dir, outputName).toFile();
            if (!outputFile.exists()) {
                LOGGER.info("!!! WARNING !!!");
                LOGGER.info("Extracting config file [{}]，to：[{}]", srcName, outputFile.getAbsolutePath());
                try (InputStreamReader reader = new InputStreamReader(ConfigKit.class.getResourceAsStream(srcName));
                     OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile))) {
                    char[] buffer = new char[1024];
                    int read;
                    while ((read = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, read);
                    }
                    writer.flush();
                }
            }
            return true;
        });
    }

    public static void checkRequired(Config args, String name, String tag) {
        if (args.notContainsName(name)) {
            throw new IllegalArgumentException("For " + tag + ", config<" + name + "> is REQUIRED !");
        }
    }

    public static void checkNotEmpty(Config args, String name, String tag) {
        if (StringKit.isEmpty(args.getString(name, null))) {
            throw new IllegalArgumentException("For " + tag + ", config<" + name + "> is REQUIRED and NOT EMPTY !");
        }
    }

}
